package com.bowlong.third.redis.lang;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.Vector;

import com.alibaba.fastjson.JSON;

import redis.clients.jedis.Jedis;

@SuppressWarnings("unchecked")
public class JedisSet<E> implements Set<E> {
	final Jedis jedis;
	final String pkey;

	public JedisSet(Jedis jedis, String pkey) {
		this.jedis = jedis;
		this.pkey = pkey;
	}

	public List<E> getAll() {
		List<E> r2 = new Vector<>();
		Set<String> datas = this.jedis.smembers(pkey);
		for (String tex : datas) {
			E e = (E) JSON.parse(tex);
			r2.add(e);
		}
		return r2;
	}

	@Override
	public int size() {
		return this.jedis.scard(pkey).intValue();
	}

	@Override
	public boolean isEmpty() {
		return size() <= 0;
	}

	@Override
	public boolean contains(Object o) {
		String tex = JSON.toJSONString(o);
		return this.jedis.sismember(pkey, tex);
	}

	@Override
	public Iterator<E> iterator() {
		List<E> datas = getAll();
		return datas.iterator();
	}

	@Override
	public Object[] toArray() {
		List<E> datas = getAll();
		return datas.toArray();
	}

	@Override
	public <T> T[] toArray(T[] a) {
		List<E> datas = getAll();
		return datas.toArray(a);
	}

	@Override
	public boolean add(E e) {
		String tex = JSON.toJSONString(e);
		this.jedis.sadd(pkey, tex);
		return true;
	}

	@Override
	public boolean remove(Object o) {
		String tex = JSON.toJSONString(o);
		this.jedis.srem(pkey, tex);
		return true;
	}

	@Override
	public boolean containsAll(Collection<?> c) {
		List<String> texs = new Vector<>();
		for (Object o : c) {
			String e = JSON.toJSONString(o);
			texs.add(e);
		}
		Set<String> datas = this.jedis.smembers(pkey);
		return datas.containsAll(texs);
	}

	@Override
	public boolean addAll(Collection<? extends E> c) {
		for (Object o : c) {
			String e = JSON.toJSONString(o);
			this.jedis.sadd(pkey, e);
		}
		return true;
	}

	@Override
	public boolean retainAll(Collection<?> c) {
		List<String> texs = new Vector<>();
		for (Object o : c) {
			String e = JSON.toJSONString(o);
			texs.add(e);
		}
		Set<String> datas = this.jedis.smembers(pkey);
		return datas.retainAll(texs);
	}

	@Override
	public boolean removeAll(Collection<?> c) {
		for (Object o : c) {
			String e = JSON.toJSONString(o);
			this.jedis.srem(pkey, e);
		}
		return true;
	}

	@Override
	public void clear() {
		this.jedis.del(pkey);
	}

}
